let $submit = $('#messageBtn')
let $messageCon = $('#messageContent')
let $id = $('#contentId')
let $comment_comments = $('.comment_comments')
let $comment_count = $('.comment_count')

// 分页
var prepage = 2
var page = 1
var pages = 0
var comments = []

// 获取评论内容
function initComment() {
  $.ajax({
    url: '/api/comment',
    data: {
      id: $id.val()
    }
  }).success(function(data) {
    if (data.code == 0) {
      comments = data.data
      renderComment()
    }
  }).error(function() {

  })
}

initComment()

$submit.on('click', function() {
  $.ajax({
    type: 'POST',
    url: '/api/comment/post',
    data: {
      contentid: $id.val(),
      content: $messageCon.val()
    }
  }).success(function(data) {
    if (data.code == 0) {
      $messageCon.val('')
      comments = data.data
      renderComment()
    }
  }).error(function() {

  })
})


function renderComment() {
  let html = ``
  const len = comments.length
  $comment_count.html(len)
  pages = Math.max(Math.ceil(len / prepage), 1);
  let start = Math.max(0, (page - 1) * prepage);
  var end = Math.min(start + prepage, len);

  let $lis = $('.pager li');
  $lis.eq(1).html(page + ' / ' + pages);

  if (page <= 1) {
    page = 1;
    $lis.eq(0).html('<span>没有上一页了</span>');
  } else {
    $lis.eq(0).html('<a href="javascript:;">上一页</a>');
  }
  if (page >= pages) {
    page = pages;
    $lis.eq(2).html('<span>没有下一页了</span>');
  } else {
    $lis.eq(2).html('<a href="javascript:;">下一页</a>');
  }

  if (comments.length == 0) {
    $('.messageList').html('<div class="messageBox"><p>还没有评论</p></div>');
  } else {
    for (var i = start; i < end; i++) {
      html += `
            <div class="messageBox">
              <p class="name clear">
                <span class="fl">${comments[i].username}</span>
                <span class="fr">${formatDate(comments[i].postTime)}</span>
              </p>
              <p>${comments[i].comtent}</p>
            </div>
                `
    }
    $comment_comments.html(html)
  }
}

$('.pager').delegate('a', 'click', function() {
  if ($(this).parent().hasClass('previous')) {
    page--
  } else {
    page++
  }
  renderComment()
});

function formatDate(d) {
  var date = new Date(d);
  return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日 ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
